import { useTagsViewStore } from '@/store/modules/tabs'
import router from '@/router'

export default {
 // 刷新当前tab页签
  refreshPage(obj: any) {
    const { path, query, matched } = router.currentRoute.value
    if (obj === undefined) {
      matched.forEach((m) => {
        if (m.components && m.components.default && m.components.default.name) {
          if (!['Layout', 'ParentView'].includes(m.components.default.name)) {
            obj = { name: m.components.default.name, path: path, query: query }
          }
        }
      })
    }
    useTagsViewStore().delCachedView(obj).then(() => {
      const { path, query } = obj
      // console.log('router',  router)
      router.replace({
        path: '/redirect' + path,
        query: query
      })
    })
    return
  },

  // Close the current tab and open a new one
  closeOpenPage(obj: any) { 
    if (obj) {
      return router.push(obj)
    }
    return useTagsViewStore().delView(router.currentRoute.value)
  },

  // Close a specific tab
  closePage(obj: any) {
    if (!obj) {
      useTagsViewStore()
        .delView(router.currentRoute.value)
        .then(({ visitedViews }) => {
          const latestView = visitedViews.slice(-1)[0]
          if (latestView && latestView.fullPath) {
            return router.push(latestView.fullPath)
          }
          return router.push('/')
        })
    }
    return useTagsViewStore().delView(obj)
  },

  // Close all tabs
  closeAllPage() {
    return useTagsViewStore().delAllViews()
  },

  // Close tabs to the left
  closeLeftPage(obj: any) {
    return useTagsViewStore().delLeftTags(obj || router.currentRoute.value)
  },

  // Close tabs to the right
  closeRightPage(obj: any) {
    return useTagsViewStore().delRightTags(obj || router.currentRoute.value)
  },

  // Close other tabs
  closeOtherPage(obj: any) {
    return useTagsViewStore().delOthersViews(obj || router.currentRoute.value)
  },

  // Open a tab
  openPage(url: string) {
    return router.push(url)
  },

  // Update a tab
  updatePage(obj: any): void {
    useTagsViewStore().updateVisitedView(obj)
  }
}
